package com.yequan.thread.atomic;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class Counter {

    private AtomicInteger atomicI = new AtomicInteger(0);

    private int i = 0;

    public static void main(String[] args) {
        final Counter counter = new Counter();
        ArrayList<Thread> threads = new ArrayList<>(600);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 10000; j++) {
                        counter.safeCount();
                        counter.unsafeCount();
                    }
                }
            });
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.start();
        }

        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("unsafeCount: " + counter.i);
        System.out.println("safeCount: " + counter.atomicI);
        System.out.println("time: " + (System.currentTimeMillis() - start));
    }

    private void safeCount() {
        for (; ; ) {
            int i = atomicI.get();
            boolean success = atomicI.compareAndSet(i, ++i);
            if (success) {
                break;
            }
        }
    }

    private void unsafeCount() {
        i++;
    }

}
